package CartService

import (
	"context"
	"database/sql"
	"gdshop-back-end-go/client-api/app/request/CartReq"
	toolsDb "gdshop-back-end-go/common/db"
	"gdshop-back-end-go/common/entity"
	"gdshop-back-end-go/common/response"
	"gdshop-back-end-go/common/response/GoodsResp"
	"gdshop-back-end-go/common/tools"
	"gdshop-back-end-go/service-member/CartService"
	"gdshop-back-end-go/service-other/GoodsService"
	"github.com/gogf/gf/frame/g"
	"time"
)

func Save(ctx context.Context, parames *CartReq.Save) *response.JsonResponse {
	return doSave(ctx, parames, "save")
}

func doSave(ctx context.Context, parames *CartReq.Save, typeString string) *response.JsonResponse {
	// 先找出是否有当前商品
	goodsModel, err := GoodsService.GetGoodsModel(ctx, parames.GoodsId)
	if err != nil {
		return tools.GetErrNoRowsResponse(err, "找不到商品", false)
	}
	optionModel := (*GoodsResp.GoodsOption)(nil)
	for _, option := range goodsModel.Options {
		if option.Id == parames.GoodsOptionId {
			optionModel = option
		}
	}
	// 找出是否有当前商品规格
	if optionModel == nil {
		return response.FailByRequestMessage(nil, "找不到规格")
	}
	// 数量是否超库存
	if parames.GoodsNum > optionModel.Stock {
		return response.FailByRequestMessage(nil, "当前规格库存不足")
	}

	// 查出当前规格是否存在购物车
	cartModel := (*entity.MemberCart)(nil)
	err = toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "member_cart").Where(
		"member_id=? AND goods_id=? AND goods_option_id=?",
		parames.MemberId,
		parames.GoodsId,
		parames.GoodsOptionId,
	).Struct(&cartModel)
	if err != nil {
		if err != sql.ErrNoRows {
			// 不是为空，返回错误
			return response.FailByRequestMessage(nil, err.Error())
		}
	}

	if cartModel == nil {
		// 不存在数据
		cartModel = &entity.MemberCart{
			MemberId:       parames.MemberId,
			StoreId:        goodsModel.StoreId,
			GoodsId:        parames.GoodsId,
			GoodsOptionId:  int(parames.GoodsOptionId),
			Total:          parames.GoodsNum,
			MarketPrice:    optionModel.MarketPrice,
			OldMarketPrice: optionModel.MarketPrice,
			SellPrice:      optionModel.SellPrice,
			OldSellPrice:   optionModel.SellPrice,
			CreateAt:       uint(time.Now().Unix()),
			IsSelected:     1,
		}
	} else {
		// 找到数据
		// 保存的模式，替换
		if typeString == "save" {
			cartModel.Total = parames.GoodsNum
		}
		// 变更模式，加入购物车模式，这时才替换 新价格
		if typeString == "change" {
			cartModel.Total = cartModel.Total + parames.GoodsNum

			// 把当前 cartModel 的价格填入老价格
			cartModel.OldSellPrice = cartModel.SellPrice
			cartModel.OldMarketPrice = cartModel.MarketPrice
			// 赋值新价格
			cartModel.MarketPrice = optionModel.MarketPrice
			cartModel.SellPrice = optionModel.SellPrice
		}

		if parames.IsSelected {
			cartModel.IsSelected = 1
		} else {
			cartModel.IsSelected = 0
		}
		cartModel.UpdateAt = uint(time.Now().Unix())
	}

	_, cartErr := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "member_cart").Save(cartModel)
	if cartErr != nil {
		return response.FailByRequestMessage(nil, cartErr.Error())
	}

	// 变更模式
	if typeString == "change" {
		// 需要删除原数据
		_, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "member_cart").Where("id", parames.CartId).Update(g.Map{
			"delete_at": time.Now().Unix(),
		})
		if err != nil {
			return response.FailByRequestMessage(nil, err.Error())
		}
	}

	return response.SuccessByRequestMessageData(nil,
		"加入购物车成功",
		CartService.BaseCount(ctx, parames.MemberId))
}
